package com.healthySys.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * JWT 创建 存储 验证
 */

@Component
@RequiredArgsConstructor
public class JWTStoreUtil {

    private final StringRedisTemplate redisTemplate; // 由Spring注入

    // 密钥（建议从配置读取，此处示例使用256位密钥）

    private static final String SECRET_STRING = "YourNewSecretKeyMustBeAtLeast32BytesLong!";
    private static final Key SECRET_KEY = new SecretKeySpec(SECRET_STRING.getBytes(StandardCharsets.UTF_8), "HmacSHA256");


    // Token有效期（毫秒）
    public static final long EXPIRATION_MS = 86400000; // 24小时

    /**
     * 创建Token（
     */
    public static String createJWT(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", username);

        return Jwts.builder()
            .setClaims(claims)
            .setSubject(username)
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_MS))
            .signWith(SECRET_KEY)
            .compact();
    }

    /**
     * 解析Token
     */
    public static Claims parseJWT(String token) {
        return Jwts.parserBuilder()
            .setSigningKey(SECRET_KEY)
            .build()
            .parseClaimsJws(token)
            .getBody();
    }

    /**
     * 验证Token
     */
    public static boolean validateJWT(String token) {
        try {
            parseJWT(token); // 能成功解析即视为有效
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 存储Token
     */
    public  void storeJWT(String username,String token , long exp){
        redisTemplate.opsForValue().set(username,token,exp, TimeUnit.MILLISECONDS);
    }

    /**
     * 验证存储的Token是否存在传入的Token
     */
    public  boolean validateStoredJWT(String username,String token){
        String storedToken = redisTemplate.opsForValue().get(username);
        return token!=null&&token.equals(storedToken);
    }

    /**
     * 移除存储的Token
     */
    public  boolean removeStoredJWT(String username){
        return redisTemplate.delete(username);
    }

    /**
     *rides是否存在指定username
     */
    public boolean containUser(String username){
        return redisTemplate.hasKey(username);
    }

    /**
     * redis中是否存在指定Token
     */
    public boolean containsToken(String token) {
        String username = parseJWT(token).getSubject();
        return validateJWT(token) && validateStoredJWT(username, token);
    }

    /**
     * redis 根据username查询Token
     */
    public String getJWTByUsername(String username) {
        return redisTemplate.opsForValue().get(username);
    }

}